//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.eResearch.RuntimeServices.Blackboard
{
    using System.Workflow.Runtime.Hosting;
    using Microsoft.Research.eResearch.Blackboard.Common;
    using Microsoft.Research.eResearch.Publisher;
    using System.ServiceModel;

    public class BlackboardService : WorkflowRuntimeService, IBlackboardService
    {
        private BlackboardPublisher publisher;
        private bool blackboardServiceConnected;

        public void PublishMessage(BlackboardMessage message)
        {
            try
            {
                if (blackboardServiceConnected)
                {
                    publisher.Publish(message);
                }
            }
            catch(EndpointNotFoundException)
            {
                // If the blackboard service is not available do not throw an exception. 
            }
        }

        public SubscriptionProfile LastSubscriptionProfile
        {
            get
            {
                return publisher.LastSubscriptionProfile;
            }
        }

        protected override void Start()
        {
            try
            {
                base.Start();
                publisher = new BlackboardPublisher();
                publisher.Start();
                blackboardServiceConnected = true;
            }
            catch(EndpointNotFoundException)
            {
                // If the blackboard service is not available do not throw an exception. 
            }
        }

        protected override void OnStarted()
        {
            base.OnStarted();
        }

        protected override void Stop()
        {
            try
            {
                if (blackboardServiceConnected)
                {
                    base.Stop();
                    publisher.Stop();
                }
                publisher = null;
                
            }
            catch (EndpointNotFoundException)
            {
                // If the blackboard service is not available do not throw an exception. 
            }
        }

        protected override void OnStopped()
        {
            base.OnStopped();
        }
    }
}
